package com.blb.edusearchservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.blb.common.entity.Course;
import com.blb.common.entity.PageEntity;
import com.blb.edusearchservice.dao.ElasticsearchDAO;
import com.blb.edusearchservice.entity.ElasticsearchEntity;
import com.blb.edusearchservice.feign.CourseServiceFeignClient;
import com.blb.edusearchservice.service.CourseIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 课程索引逻辑实现
 */
@Slf4j
@Service
public class CourseIndexServiceImpl implements CourseIndexService {

    public static final String INDEX_NAME = "course";

    @Autowired
    private CourseServiceFeignClient client;

    @Autowired
    private ElasticsearchDAO dao;

    @Override
    public void initCourseIndex() {
        try {
            if(dao.existsIndex(INDEX_NAME)){
                dao.deleteIndex(INDEX_NAME);
            }
            dao.createIndex(INDEX_NAME);
            List<Course> allCourses = client.getAllCourses();
            List<ElasticsearchEntity> list = new ArrayList<>();
            allCourses.forEach(course -> {
                list.add(new ElasticsearchEntity(course.getId().toString(),course));
            });
            dao.insertBatch(INDEX_NAME,list);
            log.info("索引库初始化完成");
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public PageEntity<Course> searchCoursePage(Map<String, String> map){
        try {
            int current = 1;
            int size = 10;
            Map<String,String> search = null;
            Map<String,String> sort = null;
            if(map.containsKey("current")){
                current = Integer.valueOf(map.get("current"));
            }
            if(map.containsKey("size")){
                size = Integer.valueOf(map.get("size"));
            }
            if(map.containsKey("search")){
                search = JSON.parseObject(map.get("search"),Map.class);
            }
            if(map.containsKey("sort")){
                sort = JSON.parseObject(map.get("sort"),Map.class);
            }
            PageEntity<Course> page = dao.searchPageByMap(INDEX_NAME, (current - 1) * size, size, search,sort,
                    Course.class);
            return page;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void saveCourse(Course course) throws IOException {
        dao.saveOrUpdate(INDEX_NAME,new ElasticsearchEntity(String.valueOf(course.getId()),course));
    }

    @Override
    public void removeCourse(String id) throws IOException {
        dao.deleteById(INDEX_NAME,id);
    }
}
